package com.swan.security.interceptor;

import com.swan.core.utils.id.IdUtil;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.MDC;
import org.springframework.security.web.session.DisableEncodeUrlFilter;

import java.io.IOException;

/** LogId自动注入 <br/>
 *  1. spring security Filter 顺序是根据继承 Filter的类型来判断的，不能自定义数值。 <br/>
 *  2. 默认顺序定义在 FilterOrderRegistration 中
 *  3. DisableEncodeUrlFilter 优先级最高
 * @author zongf
 * @date 2025-02-20
 **/
public class SecurityLogIdInjector extends DisableEncodeUrlFilter {

    private String logIdName = "LOG_ID";

    private String responseHeaderLogId = "X-Log-Id";

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        MDC.put(logIdName, IdUtil.generateLogId());

        // 在请求时，直接写入响应头，防止后续拦截器或者过滤器串改 response
        response.setHeader(this.responseHeaderLogId, MDC.get(logIdName));

        try {
            filterChain.doFilter(request, response);
        } finally {
            MDC.remove(logIdName);
        }
    }
}
